package com.iuchannel.android.provider;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.database.MatrixCursor.RowBuilder;
import android.net.Uri;
import android.util.Log;

import com.iuchannel.android.provider.Const.YT;
import com.iuchannel.android.provider.youtube.Playlist;
import com.iuchannel.android.provider.youtube.User;

public class YouTubeProvider extends ContentProvider{

	private  UriMatcher Matcher;
	private static final int MATCH_USER=0x010;
	private static final int MATCH_PLAYLIST=0x020;
	
	private void makeMatcher(){
		String packageName=getContext().getPackageName();
		String uri=packageName+".YouTubeProvider";
		
		Matcher = new UriMatcher(UriMatcher.NO_MATCH);
		Matcher.addURI(uri, YT.TABLE_USER+"/*", MATCH_USER);
		Matcher.addURI(uri, YT.TABLE_PLAYLIST+"/*", MATCH_PLAYLIST);
	}
	
	@Override
	public boolean onCreate() {
		makeMatcher();
		
		return false;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,String[] selectionArgs, String sortOrder) {
		log("Query Called : "+uri.toString());
		Cursor c=null;
		//String where = selection;		
		switch(Matcher.match(uri)){
		case MATCH_USER:
			c=queryUser(uri);
			break;
		case MATCH_PLAYLIST:
			c=queryPlaylist(uri);
			break;			
		default:
			break;
		}
		
		if(projection!=null && projection.length>0){
			log("JSON:query() - projection not null");
			if(c!=null){
				c=getCursorWithProjection(c,projection);
			}
		}
		
		return c;		
	}

	@Override
	public int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3) {
		// TODO Auto-generated method stub
		return 0;
	}
	
	@Override
	public int delete(Uri arg0, String arg1, String[] arg2) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public String getType(Uri arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Uri insert(Uri arg0, ContentValues arg1) {
		// TODO Auto-generated method stub
		return null;
	}
	
	private void log(String s){
		Log.d("YoutubeProvider", s);
	}
	
	private static Cursor getCursorWithProjection(Cursor c, String[] projection){
		MatrixCursor m=new MatrixCursor(projection);
		c.moveToFirst();
		for(int i=0;i<c.getCount();i++){
			RowBuilder r=m.newRow();
			for(String s:projection){ 
				int index=c.getColumnIndex(s);
				if(index !=-1){
					String value=c.getString(index);
					r.add(value);
				}else{
					r.add("");
				}
			}
		}
		return m;
	}
	
	private static Cursor queryPlaylist(Uri uri){
		String playlistId=uri.getLastPathSegment();
		Cursor c=Playlist.getPlaylistItem(playlistId);
		return c;
	}
	
	private static Cursor queryUser(Uri uri){
		String channelId=uri.getLastPathSegment();
		Cursor c=User.getUserPlaylist(channelId);
		return c;
	}
	
}